package com.luke.star.serviceImpl;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.alibaba.fastjson.JSON;
import com.luke.star.bean.AccessTokenRes;
import com.luke.star.bean.StException;
import com.luke.star.bean.StTaskVo;
import com.luke.star.bean.WxSendTempReq;
import com.luke.star.bean.WxSendTempRes;
import com.luke.star.bean.constant.WeiXinFinalValue;
import com.luke.star.persist.mapper.StParamMapper;
import com.luke.star.persist.mapper.StTaskMapper;
import com.luke.star.persist.mapper.StWxMsgMapper;
import com.luke.star.persist.po.StParam;
import com.luke.star.persist.po.StWxMsg;
import com.luke.star.util.DateUtil;
import com.luke.star.util.HTTPUtils;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
public class Wx001MessageService {
	
	@Resource
	private StTaskMapper stTaskMapper;
	@Resource
	private StParamMapper stParamMapper;
	@Resource
	private StWxMsgMapper stWxMsgMapper;
	
	public void sendWxMsg() throws Exception {
		List<StTaskVo> flows = stTaskMapper.queryYesterdayNote();
		Date yesterday = DateUtil.getSpecifiedDayAfter(new Date(), -1);
		String ys = DateUtil.getDateTimeToString(yesterday, "yyyy.MM.dd ")+DateUtil.getWeekDayChStr(yesterday);
		if(flows.isEmpty()) {
			log.info("{} 没有任务进度，不进行用户微信通知",ys);
			return;
		}
		Map<String, WxSendTempReq> msgmap = makeSendMsg(ys, flows);
		if(msgmap.isEmpty()) {
			log.info("{} 没有任务进度，不进行用户微信通知",ys);
			return;
		}
		log.info("{},星星勋章通知用户日简报个数：{}",ys,msgmap.size());
		
		StParam tempParam = stParamMapper.selectByPrimaryKey("template_id");
		if(tempParam==null || StringUtils.isEmpty(tempParam.getStValue())) {
			log.error("获取template_id失败");
			throw new StException("E999999999","获取template_id失败");
		}
		String accessToken = getAccessToken();
		String url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token="+accessToken;
		for(String userid:msgmap.keySet()) {
			StWxMsg wxmsg = new StWxMsg();
			wxmsg.setUserid(userid);
			wxmsg.setMsgContent(msgmap.get(userid).getTaskInfo().getValue());
			wxmsg.setCreateTime(new Date());
			wxmsg.setState("0");//0 初始 1成功 2失败
			try {
				Map<String,Object> reqmap = new HashMap<>();
				reqmap.put("touser", userid);
				reqmap.put("template_id", tempParam.getStValue());
				reqmap.put("data", msgmap.get(userid));
				String reqstr = JSON.toJSONString(reqmap);
				log.info("通知用户[{}]简报，发送给微信req:{}",userid,reqstr);
				String res = HTTPUtils.doPostJsonutf8(url, reqstr);
				log.info("通知用户[{}]简报，微信返回res:{}",userid,res);
				try {
					WxSendTempRes resbean = JSON.parseObject(res,WxSendTempRes.class);
					wxmsg.setRescode(resbean.getErrcode());
					wxmsg.setResmsg(resbean.getErrmsg());
					wxmsg.setMsgid(resbean.getMsgid());
					if("0".equals(resbean.getErrcode())) {
						wxmsg.setState("1");
					}else {
						wxmsg.setState("2");
					}
				} catch (Exception e) {
					log.error("解析json失败，简报通知失败处理,",e);
					wxmsg.setRescode("error");
					wxmsg.setResmsg("json解析异常");
					wxmsg.setState("2");
				}
					
			} catch (Exception e) {
				log.error("通知用户[{}]简报时发生异常,",userid,e);
				wxmsg.setRescode("error");
				wxmsg.setResmsg("系统异常");
				wxmsg.setState("2");
			}
			stWxMsgMapper.insertSelective(wxmsg);
		}
		
	}
	
	private String getAccessToken() throws IOException {
		String access_token = "";
		StParam param = stParamMapper.selectByPrimaryKey("access_token");
		if(param != null && param.getUpdateTime()!=null) {
			Date updateTime = param.getUpdateTime();
			Date nowDate = new Date();
			if(nowDate.getTime()-updateTime.getTime() < 7000*1000) {//有效时间2小时
				access_token = param.getStValue();
			}
		}
		
		if(StringUtils.isEmpty(access_token)) {
			String url=WeiXinFinalValue.GET_ACCESSTOKEN;
			url=url.replace("APPID", WeiXinFinalValue.APPID).replace("APPSECRET", WeiXinFinalValue.APPSECRET);
			String res = HTTPUtils.doGetUtf8(url);
			log.info("请求获取access_token响应报文 res:{}",res);
			AccessTokenRes resbean = JSON.parseObject(res,AccessTokenRes.class);
			if(StringUtils.isEmpty(resbean.getAccess_token())) {
				log.error("获取access_token失败");
				throw new StException("E999999999","获取access_token失败");
			}else {
				access_token = resbean.getAccess_token();
				if(param != null) {
					StParam record = new StParam();
					record.setStKey("access_token");
					record.setStValue(access_token);
					record.setUpdateTime(new Date());
					stParamMapper.updateByPrimaryKeySelective(record);
				}else {
					StParam record = new StParam();
					record.setStKey("access_token");
					record.setStValue(access_token);
					record.setRemark("微信token");
					record.setCreateTime(new Date());
					record.setUpdateTime(new Date());
					stParamMapper.insertSelective(record);
				}
				
			}
		}
		
		return access_token;
	}
	
	
	private Map<String,WxSendTempReq> makeSendMsg(String ys,List<StTaskVo> flows){
		Map<String,WxSendTempReq> msgmap = new HashMap<>();
		for(StTaskVo flow:flows) {
			if(flow.getAddStarNum() == 0) {
				continue;
			}
			String userid = flow.getUserid();
			WxSendTempReq msg = msgmap.get(userid);
			if(msg == null) {
				msg = new WxSendTempReq();
				msg.getTaskTime().setValue(ys);
				msg.getTaskInfo().setValue("");
				msgmap.put(userid, msg);
			}
			BigDecimal expect = new BigDecimal(flow.getExpectNum());
			BigDecimal nownum = new BigDecimal(flow.getStarNum());
			BigDecimal divide = nownum.multiply(new BigDecimal("100")).divide(expect,1,BigDecimal.ROUND_HALF_UP);
			String percent = "("+divide.toString()+"%); ";
			
			String addstar = " +"+flow.getAddStarNum();
			if(flow.getAddStarNum()<0) {
				addstar = " "+flow.getAddStarNum();
			}
			String msgstr = flow.getTaskName()+addstar+percent;
			msg.getTaskInfo().setValue(msg.getTaskInfo().getValue()+msgstr);
		}
		return msgmap;
	}
	
	
	
}














